import { ajax } from '../../utils/util.js'
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
var tempFilePath;
let app = getApp().globalData;
let audioIcon = app.fileUrl + '95e625c7565c03247bb383de53047ce8_180_180.jpeg';
let playIcon = app.fileUrl + '248fdd4383905e05ee65f891fce5e36c_100_100.jpeg';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    audioIcon,
    playIcon,
    arrowSrc: 'https://bpic.588ku.com/element_pic/00/96/10/4456f2f6f075d88.jpg!/fw/254/quality/90/unsharp/true/compress/true',
    grades:['青铜','白银','黄金','铂金','钻石','大师','王者'],
    grade:'',
    description:'',
    imgSrc:'',
    coverSrc:'',
    audioSrc:'',
    setskillIntroduce:'',
    imgIsSuccess:false,
    audioIsSuccess:false,
    coverIsSuccess:false,
    skill:{},
    soundRecordShow: false,//弹出层的显示隐藏
    secondNum: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let skill = JSON.parse(options.skill);
    
    this.setData({ skill})

    //设置标题
    wx.setNavigationBarTitle({
      title: skill.title+'陪练资质'
    })
    console.log(app.scopeRecord);
    // if (!app.scopeRecord) {
	//
    //   wx.openSetting({
    //     success(){
    //       app.scopeRecord=true;
    //     }
    //   });
    // }
  },

  getScopeRecord() {
    wx.getSetting({
      success(res) {
        console.log(res);
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success() {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              wx.startRecord()
            }
          })
        }
      }
    })
  },


  //选择资质图片
  chooseImage(){
    let self=this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res){
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        self.setData({ imgSrc: tempFilePaths });

        wx.getImageInfo({
          src: tempFilePaths[0],
          success(imgInfo){
            wx.showToast({
              title: '正在上传...',
              icon: 'loading',
              mask: true,
              duration: 1000
            })  

            let cover = JSON.stringify({
              url: tempFilePaths[0],
              width: imgInfo.width,
              height: imgInfo.height,
            })
            wx.uploadFile({
              url: 'http://api.tanwancat.com/file/uploadimage',
              filePath: tempFilePaths[0],
              header: {
                "Content-Type": "multipart/form-data"
              },
              name: 'file',
              formData: {
                //token: wx.getStorageSync('Cookie'),
              },
              suceess:function(res) {
                
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  mask: true,
                  duration: 1000
                })
                self.setData({ imgSrc: app.fileUrl + res.data, imgIsSuccess:true });
                console.log(self.data.imgIsSuccess);
              
              },

              fail:function(err) {
                console.log(err);
              },
              complete:function(res){
                let data=JSON.parse(res.data);
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  mask: true,
                  duration: 1000
                })

                if (data.code==0){
                  console.log(self);
                  self.setData({ imgSrc: app.fileUrl + data.data, imgIsSuccess: true });
                }
              },
            })

          }
        })


        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        
        
        
        
        
      }
    })
  },

  //查看图片 
  previewImage(){
    wx.previewImage({
      current: this.data.imgSrc, 
      urls: [this.data.imgSrc] // 
    })
  },

  //选择封面图片
  chooseCoverImage() {
    let self = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        self.setData({ coverSrc: tempFilePaths });

        wx.getImageInfo({
          src: tempFilePaths[0],
          success(imgInfo) {
            wx.showToast({
              title: '正在上传...',
              icon: 'loading',
              mask: true,
              duration: 1000
            })

            let cover = JSON.stringify({
              url: tempFilePaths[0],
              width: imgInfo.width,
              height: imgInfo.height,
            })
            wx.uploadFile({
              url: 'http://api.tanwancat.com/file/uploadimage',
              filePath: tempFilePaths[0],
              header: {
                "Content-Type": "multipart/form-data"
              },
              name: 'file',
              formData: {
                //token: wx.getStorageSync('Cookie'),
              },
              suceess: function (res) {

                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  mask: true,
                  duration: 1000
                })
                self.setData({ coverSrc: app.fileUrl + res.data, coverIsSuccess: true });
                

              },

              fail: function (err) {
                console.log(err);
              },
              complete: function (res) {
                let data = JSON.parse(res.data);
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  mask: true,
                  duration: 1000
                })

                if (data.code == 0) {
                  console.log(self);
                  self.setData({ coverSrc: app.fileUrl + data.data, coverIsSuccess: true });
                }
              },
            })

          }
        })


        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片

      }
    })
  },

  //查看图片 
  previewCoverImage() {
    wx.previewImage({
      current: this.data.coverSrc,
      urls: [this.data.coverSrc]  
    })
  },

  //关闭录音弹出层
  closeSoundRecord() {
    this.setData({
      soundRecordShow: false,
    })
  },

  //测试长按语音
  testRecord() {
    const options = {
      duration: 10000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
      frameSize: 50
    }

    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    recorderManager.onError((res) => {
      console.log(res);
    })

    let secondNum = this.data.secondNum;
    //自定义属性接收定时器的返回值 用来清除
    this.recordTime = setInterval(() => {
      secondNum++;
      this.setData({
        secondNum
      })
    }, 1000);

  },



  //测试长按语音抬起
  testRecordUp() {
    let self = this;

    //手抬起清楚定时器
    clearInterval(this.recordTime);

    recorderManager.stop();
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res.tempFilePath);
     
      const { tempFilePath } = res
    })
  },
  uploadAudio() {
    let self = this;
    wx.uploadFile({
      url: 'http://api.tanwancat.com/file/uploadaudio',
      filePath: this.tempFilePath,
      header: {
        "Content-Type": "multipart/form-data"
      },
      name: 'file',
      formData: {
        token: wx.getStorageSync('Cookie'),

      },
      suceess(res) {
        console.log(res);
        wx.showToast({
          icon: 'success',
          title: '上传成功',
        })
        self.setData({ audioSrc: res.url, });

      },

      fail(err) {
        console.log(err);
      },
      complete: function (res) {
        console.log(res);
        let data = JSON.parse(res.data);

        if (data.code == 0) {
          wx.showToast({
            icon: 'success',
            title: '上传成功',
          })
          self.setData({ audioSrc: app.fileUrl+data.data, audioIsSuccess: true});

        }
      },
    })
  },

  againAudio() {
    this.setData({
      secondNum: 0
    })
  },

 //录音
  recorderClick(){

    this.setData({
      soundRecordShow: true,
    })
    return;
  },

  endAudio(){
    let self=this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res.tempFilePath);

      wx.uploadFile({
        url: 'http://api.tanwancat.com/file/uploadaudio',
        filePath: this.tempFilePath,
        header: {
          "Content-Type": "multipart/form-data"
        },
        name: 'file',
        formData: {
          skill_id: this.data.skill.skill_id,
          token: wx.getStorageSync('Cookie'),

        },
        suceess(res) {
          console.log(res);
          self.setData({ audioSrc: res.url, audioIsSuccess:true });
        },

        fail(err) {
          console.log(err);
        },
        complete: function (res) {
          console.log(res);
          let data = res.data;

          if (data.code == 0) {
            self.setData({ audioSrc: data.url, audioIsSuccess: true });
          }
        },
      })
      const { tempFilePath } = res
    })
  },
  playAudio(){
    console.log(this.tempFilePath);
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })

  },

  bindPickerChange(e) {
    let index = e.detail.value;
    let grade = this.data.grades.find((item, ind) => ind == index);
    this.setData({ grade });
  },

  setskillIntroduce(e){
    this.setData({
      description: e.detail.value
    })
  },


  submitInfo(){
    
    if (!this.data.imgIsSuccess){
     
      wx.showToast({
        title: '请上传资质图片',
        icon: 'loading',
        duration: 800,
      })
      return;
    }
    // if (!this.data.audioIsSuccess) {
    //   wx.showToast({
    //     title: '请上传语音',
    //     icon: 'loading',
    //     duration: 800,
    //   })
    //   return;
    // }

    if (!this.data.grade) {
      wx.showToast({
        title: '请选择等级',
        icon: 'loading',
        duration: 800,
      })
      return;
    }
    if (!this.data.description) {
        wx.showToast({
            title: '请填写技能说明',
            icon: 'loading',
            duration: 800,
        })
        return;
    }


    let json={
      token: wx.getStorageSync('Cookie'),
      skill_id:this.data.skill.skill_id,
      level: this.data.grade,
      cover: this.data.coverSrc,
      audio: JSON.stringify({ url: this.data.audioSrc, duration: this.data.secondNum }),
      description: this.data.setskillIntroduce,
      skillcover: this.data.imgSrc,}
    ajax('seller/apply',json).then(res=>{
      wx.showToast({
        title: '请耐心等待审核',
        icon: 'success',
        image: '',
        duration: 1500,
        mask: true,
        success: function (res) {
			wx.redirectTo({
				url: '../review/review'
			})
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})